package cn.com.ddapp.ddm.ui.order;


import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.text.TextUtils;
import android.view.Display;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.jungly.gridpasswordview.GridPasswordView;

import java.util.Map;

import butterknife.BindView;
import cn.com.ddapp.ddm.AppConfig;
import cn.com.ddapp.ddm.R;
import cn.com.ddapp.ddm.api.OKUtilAPI;
import cn.com.ddapp.ddm.base.ActivityManager;
import cn.com.ddapp.ddm.base.BaseActivity;
import cn.com.ddapp.ddm.base.BaseApplication;
import cn.com.ddapp.ddm.bean.mine.UserData;
import cn.com.ddapp.ddm.bean.order.AlipayCodeEntity;
import cn.com.ddapp.ddm.bean.order.OrderPriceEntity;
import cn.com.ddapp.ddm.bean.settleShopcar.SettleAccountsEntity;
import cn.com.ddapp.ddm.inter.OkUtilCallback;
import cn.com.ddapp.ddm.pay.PayCallback;
import cn.com.ddapp.ddm.pay.alipay.AlipayProvider;
import cn.com.ddapp.ddm.pay.alipay.PayObject;
import cn.com.ddapp.ddm.pay.wx.WXProvider;
import cn.com.ddapp.ddm.pay.wx.WXProviderScan;
import cn.com.ddapp.ddm.polling.PollingService;
import cn.com.ddapp.ddm.polling.PollingUtils;
import cn.com.ddapp.ddm.ui.dialog.CommonDialog;
import cn.com.ddapp.ddm.ui.dialog.DialogHelper;
import cn.com.ddapp.ddm.ui.empty.EmptyLayout;
import cn.com.ddapp.ddm.util.QRUtil;
import cn.com.ddapp.ddm.util.SPUtils;
import cn.com.ddapp.ddm.util.TDevice;
import cn.com.ddapp.ddm.util.TLog;

/**
 * Created by caopenghui on 2016-08-03.
 */
public class PayActivity extends BaseActivity implements View.OnClickListener{

    @BindView(R.id.title)
    TextView title;

    @BindView(R.id.action)
    TextView action;

    @BindView(R.id.back)
    ImageView back;

    @BindView(R.id.checkboxWechat)
    ImageView checkboxWechat;
    @BindView(R.id.checkboxAlipay)
    ImageView checkboxAlipay;
//    @BindView(R.id.checkboxBank)
//    ImageView checkboxBank;
    @BindView(R.id.checkboxWallet)
    ImageView checkboxWallet;

    @BindView(R.id.pay)
    TextView pay;

    @BindView(R.id.error_layout)
    EmptyLayout mEmptyLayout;
    @BindView(R.id.price)
    TextView priceTextView;
    private int payType=1;//1微信支付 2 支付宝支付 3银联支付 4钱包支付
    private OrderPriceEntity entity;
    private Double price=0.00;
    private Dialog dialog;
    private boolean isRegister = false;
    private GridPasswordView gpw;
    boolean payPwdIfSet = false;
    int  orderid ;
    @Override
    public void initView() {
        title.setText(BaseApplication.getIntstance().getResources().getString(R.string.order_pay));
        action.setVisibility(View.GONE);
        back.setVisibility(View.VISIBLE);
        back.setOnClickListener(this);
        checkboxWechat.setOnClickListener(this);
        checkboxAlipay.setOnClickListener(this);
//        checkboxBank.setOnClickListener(this);
        checkboxWallet.setOnClickListener(this);
        pay.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        if(v.getId()==back.getId()){
            ActivityManager.getInstance().finishActivity();
        }else if(v.getId()==checkboxWechat.getId()){
            payType=1;
            clearImgs();
            checkboxWechat.setImageResource(R.mipmap.right);
        }
        else if(v.getId()==checkboxAlipay.getId()){
            payType=2;
            clearImgs();
            checkboxAlipay.setImageResource(R.mipmap.right);
        }
// else if(v.getId()==checkboxBank.getId()){
//            payType=3;
//            clearImgs();
//            checkboxBank.setImageResource(R.mipmap.right);
//        }
        else if(v.getId()==checkboxWallet.getId()){
            payType=4;
            clearImgs();
            checkboxWallet.setImageResource(R.mipmap.right);
        }else if(v.getId()==pay.getId()){
            payAction();
        }
    }

    private void payAction() {

        if(price<=0.00){
            BaseApplication.showToast(R.string.price_error);
            return;
        }
        if(payType==1&&!TDevice.isTablet(getApplicationContext())){
            //微信支付
            PayObject payObject = new PayObject();
            payObject.setBody(getIntent().getStringExtra("goodsName"));
            payObject.setName(getIntent().getStringExtra("goodsName"));
            payObject.setPrice(price+"");
//            payObject.setPrice(0.10+"");
            payObject.setOrderNo(getIntent().getStringExtra("orderNo"));
//            payObject.setOrderId(entity.getOrder().getOrderNo());
            payObject.setNotify_url(OKUtilAPI.WEIXINPAY_CALLBACK);
            WXProvider wxProvider = new WXProvider(PayActivity.this,payObject);
            wxProvider.pay();
            IntentFilter intentFilter = new IntentFilter(PollingService.ACTION);
            isRegister = true;
            registerReceiver(receiver,intentFilter);
        } else if(payType==1&& TDevice.isTablet(getApplicationContext())){
            //平板微信支付 微信扫码支付
            PayObject payObject = new PayObject();
            payObject.setBody(getIntent().getStringExtra("goodsName"));
            payObject.setName(getIntent().getStringExtra("goodsName"));
            payObject.setPrice(price+"");
//            payObject.setPrice(0.10+"");
            payObject.setOrderNo(getIntent().getStringExtra("orderNo"));
//            payObject.setOrderId(entity.getOrder().getOrderNo());
            payObject.setNotify_url(OKUtilAPI.SCAN_CALLBACK);
            WXProviderScan wxProvider = new WXProviderScan(PayActivity.this,payObject);
            wxProvider.setCodeUrlSuccessListener(new WXProviderScan.CodeUrlSuccessListener() {
                @Override
                public void onCodeUrlSuccessListerer(Map<String, String> result) {
                    if("fail".equalsIgnoreCase(result.get("result_code"))){
                        BaseApplication.showToast(result.get("err_code_des"));
                    }else if("success".equalsIgnoreCase(result.get("result_code"))){
                        System.out.println("huag"+result.get("code_url"));
                        dialog = new Dialog(PayActivity.this, R.style.Transparent);
                        dialog.setContentView(R.layout.dialog_pay_qr);
                        dialog.setCanceledOnTouchOutside(true);
                        ImageView bitmap = (ImageView)dialog.findViewById(R.id.qr);
                        bitmap.setImageBitmap(QRUtil.createQRImage(result.get("code_url"),200,200));

                        Window win = dialog.getWindow();
                        win.setGravity( Gravity.CENTER);
//                        win.getDecorView().setPadding(0, 0, 0, 0);
                        WindowManager.LayoutParams lp = win.getAttributes();
                        lp.width = WindowManager.LayoutParams.WRAP_CONTENT;
                        lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
                        lp.flags = WindowManager.LayoutParams.FLAG_DIM_BEHIND;
                        lp.dimAmount = 0.5f;
                        win.setAttributes(lp);
                        dialog.show();
                        IntentFilter intentFilter = new IntentFilter(PollingService.ACTION);
                        isRegister = true;
                        registerReceiver(receiver,intentFilter);
                        PollingUtils.startPollingService(PayActivity.this, 1, PollingService.class, PollingService.ACTION,getIntent().getStringExtra("orderNo"),PollingService.WECAHT);
                    }
                }
            });
            wxProvider.pay();
        }else if(payType==4){
            walletPay();
        }else if(payType==2&&!TDevice.isTablet(getApplicationContext())){
            //支付宝支付
            PayObject payObject = new PayObject();
            payObject.setBody(getIntent().getStringExtra("goodsName"));
            payObject.setName(getIntent().getStringExtra("goodsName"));
            payObject.setPrice(price+"");
//            payObject.setPrice(0.10+"");
            payObject.setOrderNo(getIntent().getStringExtra("orderNo"));
            payObject.setNotify_url(OKUtilAPI.ALIPAYPAY_CALLBACK);
            AlipayProvider alipayProvider = new AlipayProvider(PayActivity.this,payObject, new PayCallback() {
                @Override
                public void callback(int paycode) {
                    System.out.println("支付宝回调");
                    if(paycode==AlipayProvider.PAY_SUCCESS){
                        BaseApplication.showToast(R.string.pay_success);
                        Intent intent1 = new Intent(PayActivity.this,OrderDetailActivity.class);
                        intent1.putExtra("orderId",orderid);
                        startActivity(intent1);
                        finish();
                    }else{
                        BaseApplication.showToast(R.string.pay_failed);
                    }
                }
            });
            alipayProvider.pay();
        }
        else if(payType==2&&TDevice.isTablet(getApplicationContext())){
            showWaitDialog("正在获取预支付交易...");

            final OkUtilCallback okUtilCallback = new OkUtilCallback(){
                @Override
                public void onMyResponse(String response, int id) {
                    hideWaitDialog();
                    TLog.log("支付宝扫码支付===",response);
                    AlipayCodeEntity entity = gson.fromJson(response,AlipayCodeEntity.class);
                    if((!AppConfig.RESULT_OK.equalsIgnoreCase(entity.getResult()))){
                        BaseApplication.getIntstance().showToast(entity.getResult(), Toast.LENGTH_SHORT,0, Gravity.TOP);
                    }else if((AppConfig.RESULT_OK.equalsIgnoreCase(entity.getResult()))){
                        System.out.println("huag"+entity.getCodeUrl());
                        dialog = new Dialog(PayActivity.this, R.style.Transparent);
                        dialog.setContentView(R.layout.dialog_pay_qr_alipay);
                        dialog.setCanceledOnTouchOutside(true);
                        ImageView bitmap = (ImageView)dialog.findViewById(R.id.qr);
                        bitmap.setImageBitmap(QRUtil.createQRImage(entity.getCodeUrl(),200,200));

                        Window win = dialog.getWindow();
                        win.setGravity( Gravity.CENTER);
//                        win.getDecorView().setPadding(0, 0, 0, 0);
                        WindowManager.LayoutParams lp = win.getAttributes();
                        lp.width = WindowManager.LayoutParams.WRAP_CONTENT;
                        lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
                        lp.flags = WindowManager.LayoutParams.FLAG_DIM_BEHIND;
                        lp.dimAmount = 0.5f;
                        win.setAttributes(lp);
                        dialog.show();
                        IntentFilter intentFilter = new IntentFilter(PollingService.ACTION);
                        isRegister = true;
                        registerReceiver(receiver,intentFilter);
                        PollingUtils.startPollingService(PayActivity.this, 1, PollingService.class, PollingService.ACTION,getIntent().getStringExtra("orderNo"),PollingService.ALIPAY);
                    }
                }
            };
            OKUtilAPI.post(OKUtilAPI.ALYPAY_CODE, "&orderNo="+getIntent().getStringExtra("orderNo"), okUtilCallback);
        }
    }

    private void walletPay() {
        if(price<=0.00){
            BaseApplication.showToast(R.string.price_error);
            return;
        }
        payPwdIfSet();
    }

    private void  clearImgs(){
        checkboxWechat.setImageResource(R.drawable.circle_unchecked);
        checkboxAlipay.setImageResource(R.drawable.circle_unchecked);
//        checkboxBank.setImageResource(R.drawable.circle_unchecked);
        checkboxWallet.setImageResource(R.drawable.circle_unchecked);
    }

    @Override
    public void initData() {
        requestData();
    }

    private String getActivityTag(){
        return PayActivity.class.getSimpleName();
    };

    private void requestData() {
        {
            mEmptyLayout.setErrorType(EmptyLayout.NETWORK_LOADING);
            String userId =  SPUtils.getStringData(this, SPUtils.USERID);
            final OkUtilCallback okUtilCallback =  new OkUtilCallback(mEmptyLayout) {
                @Override
                public void onMyResponse(String response, int id) {
                    TLog.log(getActivityTag(),response);
                    entity = gson.fromJson(response,OrderPriceEntity.class);
                    if((!AppConfig.RESULT_OK.equalsIgnoreCase(entity.getResult()))&&entity.getLogin()){
                        mEmptyLayout.setErrorType(EmptyLayout.NO_LOGIN);
                    }else if((!AppConfig.RESULT_OK.equalsIgnoreCase(entity.getResult()))){
                        BaseApplication.getIntstance().showToast(entity.getResult(), Toast.LENGTH_SHORT,0, Gravity.CENTER);
                    }else{
                        orderid = entity.getOrder().getId();
                        price=getIntent().getDoubleExtra("goodsCurPrice",entity.getOrder().getJiaoyiAmount());
                        priceTextView.setText(AppConfig.MONEY_SYMBEL+price);
                    }
                }
            };
            OKUtilAPI.post(OKUtilAPI.ORDER_PRICE, "userId="+userId+"&orderNum="+getIntent().getStringExtra("orderNo"), okUtilCallback);
        }
    }

    @Override
    public int getContentViewId() {
        return R.layout.pay_activity;
    }

    @Override
    protected String getFragmentTag() {
        return PayActivity.class.getSimpleName();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if(isRegister){
            unregisterReceiver(receiver);
            PollingUtils.stopPollingService(this, PollingService.class, PollingService.ACTION);
        }

    }

    CommonDialog dialogPay ;
    /**
     * 获取用户信息
     */
    private void payPwdIfSet() {
        dialogPay = DialogHelper.getPinterestDialogCancelable(PayActivity.this);
        String userId = SPUtils.getStringData(PayActivity.this, SPUtils.USERID);;
        final OkUtilCallback okUtilCallback = new OkUtilCallback(){
            @Override
            public void onMyResponse(String response, int id) {
                hideWaitDialog();
                TLog.log(getFragmentTag(),response);
                UserData entity = gson.fromJson(response,UserData.class);
                if((!AppConfig.RESULT_OK.equalsIgnoreCase(entity.getResult()))&&entity.getLogin()){
                    mEmptyLayout.setErrorType(EmptyLayout.NO_LOGIN);
                }else if((!AppConfig.RESULT_OK.equalsIgnoreCase(entity.getResult()))){
                    BaseApplication.getIntstance().showToast(entity.getResult(), Toast.LENGTH_SHORT,0, Gravity.TOP);
                }else if((AppConfig.RESULT_OK.equalsIgnoreCase(entity.getResult()))){
                    payPwdIfSet = entity.isPayPwdIfSet();
                    if(!payPwdIfSet){
                        BaseApplication.showToast(R.string.no_pay_pwd);
                        return;
                    }else{
                        dialogPay.setContent(getLayoutInflater().inflate(R.layout.dialog_paypwd, (ViewGroup) findViewById(R.id.dialog_paypwd)));
//                        dialogPay.setNegativeButton("取消", new DialogInterface.OnClickListener() {
//                            @Override
//                            public void onClick(DialogInterface dialogInterface, int i) {
//                                dialogPay.dismiss();
//                            }
//                        });
                        WindowManager m = getWindowManager();
                        Window dialogWindow = dialogPay.getWindow();
                        Display d = m.getDefaultDisplay(); // 获取屏幕宽、高用
                        WindowManager.LayoutParams p = dialogWindow.getAttributes(); // 获取对话框当前的参数值
                        p.height = (int) (d.getHeight() * 0.5); // 高度设置为屏幕的0.6
                        p.width = (int) (d.getWidth() * 1); // 宽度设置为屏幕的0.65
                        dialogWindow.setAttributes(p);
                        dialogPay.show();
                        gpw = (GridPasswordView) dialogPay.findViewById(R.id.gpv_tx);
                        Button negative= (Button) dialogPay.findViewById(R.id.negative);
                        negative.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                dialogPay.dismiss();
                            }
                        });
                        gpw.setOnPasswordChangedListener(new GridPasswordView.OnPasswordChangedListener() {
                            @Override
                            public void onTextChanged(String psw) {

                            }

                            @Override
                            public void onInputFinish(String psw) {
                                walletPaying(psw);
                            }
                        });
                    }
                }
            }
        };
        OKUtilAPI.post(OKUtilAPI.getUser, "userId=" + userId , okUtilCallback);
    }

    /**
     * 去结算
     */
    private void walletPaying(String psw) {


        showWaitDialog(R.string.paying);

        String userId = SPUtils.getStringData(PayActivity.this, SPUtils.USERID);;
        final OkUtilCallback okUtilCallback = new OkUtilCallback(){
            @Override
            public void onMyResponse(String response, int id) {
                hideWaitDialog();
                TLog.log("钱包支付===",response);
                SettleAccountsEntity entity = gson.fromJson(response,SettleAccountsEntity.class);
                if((!AppConfig.RESULT_OK.equalsIgnoreCase(entity.getResult()))&&entity.getLogin()){
                    mEmptyLayout.setErrorType(EmptyLayout.NO_LOGIN);
                }else if((!AppConfig.RESULT_OK.equalsIgnoreCase(entity.getResult()))){
                    BaseApplication.getIntstance().showToast(entity.getResult(), Toast.LENGTH_SHORT,0, Gravity.TOP);
                }else if((AppConfig.RESULT_OK.equalsIgnoreCase(entity.getResult()))){
                    BaseApplication.showToast(R.string.pay_success);
                    if(dialogPay!=null)
                    dialogPay.dismiss();
                    Intent intent1 = new Intent(PayActivity.this,OrderDetailActivity.class);
                    intent1.putExtra("orderId",orderid);
                    startActivity(intent1);
                    finish();
                }
            }
        };
        OKUtilAPI.post(OKUtilAPI.WALLET_PAY, "userId=" + userId+"&orderNum="+getIntent().getStringExtra("orderNo")+"&payPassword="+psw+"&amount="+price*100, okUtilCallback);
    }



    private BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String status = intent.getStringExtra("status");
            System.out.println("huag"+intent.getStringExtra("status"));
            if("2".equalsIgnoreCase(status)){
                if(isRegister){
                    unregisterReceiver(receiver);
                    isRegister = false;
                    PollingUtils.stopPollingService(PayActivity.this, PollingService.class, PollingService.ACTION);
                }
                BaseApplication.showToast(R.string.pay_success);
                Intent intent1 = new Intent(PayActivity.this,OrderDetailActivity.class);
                intent1.putExtra("orderId",orderid);
                startActivity(intent1);
                finish();
                if(dialog!=null){
                    dialog.dismiss();
                }
            }

//            if(intent.getAction().equals("com.ryantang.service.PollingService")){
//                System.out.println("微信支付回调");
//                BaseApplication.showToast(R.string.pay_success);
//                Intent intent1 = new Intent(PayActivity.this,OrderDetailActivity.class);
//                intent1.putExtra("orderId",orderid);
//                startActivity(intent1);
//                finish();
//            }
        }
    };
}
